package com.zhang.util;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 获取链接操作
 */
public class HttpUtils {

    /**
     * 获取链接
     * @param url 文件地址
     */
    public static HttpURLConnection getHttpUrlConnection(String url) throws IOException {
        URL httpUrl = new URL(url);
        //打开链接
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
        //发送标识信息
        httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0(compatible;MSIE9.0;WindowsNT6.1;Trident/5.0");
        return httpURLConnection;
    }

    /**
     * 获取文件名
     * @param url
     * @return
     */
    public static String getHttpFileName(String url){
        int index = url.lastIndexOf("/");
        return url.substring(index + 1);
    }

    /**
     * 文件切分
     * @param url 文件下载地址
     * @param startPos 开始位置
     * @param endPos 结束位置
     */
    public static HttpURLConnection getHttpFileSegmentation(String url, Long startPos, Long endPos) throws IOException {
        //获取链接
        HttpURLConnection httpUrlConnection = getHttpUrlConnection(url);
        LogUtils.info("分片下载：{} --- {} ", startPos, endPos);
        //中间数据块
        if (endPos != 0) {
            //bytes=100-200
            httpUrlConnection.setRequestProperty("RANGE", "bytes=" + startPos + "-" + endPos);
        } else {
            httpUrlConnection.setRequestProperty("RANGE", "bytes=" + startPos + "-");
        }
        return httpUrlConnection;
    }

    /**
     * 获取下载文件大小
     * @param url
     * @return
     * @throws IOException
     */
    public static long getHttpFileConstantLength(String url) throws IOException {
        int contentLength;
        HttpURLConnection httpUrlConnection = null;
        try {
            httpUrlConnection = getHttpUrlConnection(url);

            contentLength = httpUrlConnection.getContentLength();
        } finally {
            if (httpUrlConnection != null) {

                httpUrlConnection.disconnect();
            }
        }
        return contentLength;

    }

}
